package com.ai.nsa.actions;

import com.ai.nsa.DefaultNSATableRoute;
import com.ai.nsa.NSATableRoute;
import com.ai.nsa.NSATables;
import com.ai.nsa.utils.hbase.HBaseOperations;
import com.ai.nsa.utils.hbase.model.HBaseRow;
import com.asiainfo.appserver.Action;
import com.asiainfo.appserver.Request;
import com.asiainfo.appserver.Response;
import com.asiainfo.appserver.annotations.Function;
import com.asiainfo.appserver.annotations.Parameter;
import com.asiainfo.appserver.annotations.Type;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Collections;
import java.util.Map;

import static com.ai.nsa.NSAConstants.HBASE_FAMILY;
import static com.ai.nsa.NSAConstants.UNDERLINE;

/**
 * @author Feng Chen 2017/6/8.
 */
@Function(description = "日志检索(单条)", parameters = {
        @Parameter(name = "ROW_KEY", type = Type.String, description = "行键", required = true),
        @Parameter(name = "INTERACT_TYPE", type = Type.String, description = "交互类型", required = true)
})
@Component
public class NSAGet implements Action {

    @Autowired
    private HBaseOperations hbase;

    @Autowired
    private NSATables tables;

    private NSATableRoute tableRoute = new DefaultNSATableRoute();

    private static final Logger logger = LoggerFactory.getLogger(NSAGet.class);

    public Response execute(Request request) throws Exception {
        String rowkey = request.getString("ROW_KEY");
        String interactType = request.getString("INTERACT_TYPE");
        try {

            Map<String, String> row = get(rowkey, interactType, new Extracter<HBaseRow, Map<String, String>>() {

                @Override
                public Map<String, String> extract(HBaseRow row) {

                    if (row == null) {
                        return Collections.emptyMap();
                    }

                    return row.getFamily(HBASE_FAMILY);
                }

            });

            return Response.success().put("row", row);
        } catch (Exception e) {
            logger.error("", e);
            return Response.fail(e);
        }
    }

    // SECTION: INNER HELPER

    private Map<String, String> get(String rowkey, String interactType, Extracter<HBaseRow, Map<String, String>> extracter) {
        HBaseRow row = hbase.get(tables.get(interactType) + UNDERLINE + tableRoute.getTable(rowkey), rowkey);
        return extracter.extract(row);
    }

    //////////////////////////////////////////////////////////////////

    private interface Extracter<F, T> {

        T extract(F f);

    }

}